package com.surelution.cppei.weixin.gate

import com.surelution.whistle.push.OAuthHelper

class BranchController {
	
	def subscriberFollowSubAccountService

    def index() {
		def code = params.code
		if(!code) {
			render(view:'forbidden')
			return
		}
		def openid = OAuthHelper.getOpenidByCode(code)
		def subscriber = Subscriber.findByOpenId(openid)
		if(!subscriber?.account) {
			redirect(action:'show', id:subscriber?.id)
			return
		} else {
			redirect(url:subscriber.account.subAccount.homePageUrl)
		}
	}
	
	def show(Long id) {
		def subscriber = Subscriber.get(id)
		def branches = SubAccount.findAllByEnabled(true)
		[branches:branches, subscriber:subscriber]
	}

	def saveBranch() {
		def subscriberId = params["subscriber.id"]
		def branchId = params["branch.id"]
		def subscriber = Subscriber.get(subscriberId)
		def branch = SubAccount.get(branchId)
		subscriberFollowSubAccountService.follow(subscriber, branch)
		redirect(action:'show', id:subscriber.id)
	}
}
